<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级" prop="classId">
        <el-select v-model="queryParams.classId" clearable filterable placeholder="请选择班级">
          <el-option
            v-for="item in classList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
       <el-form-item label="月份" prop="weekNumber">
          <!-- <el-input v-model="queryParams.weekNumber" placeholder="请输入月份" /> -->
          <el-date-picker
                size="small"
                v-model="queryParams.monthId"
                type="month"
                value-format="yyyy-MM"
                placeholder="请选择月份"
              >
              </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="weeklyplanList"
    >
      <el-table-column label="班级ID" align="center" prop="className" />
      <el-table-column label="学期" align="center" prop="semsterName" />
      <el-table-column label="日期" align="center" prop="monthTime" />

      <el-table-column label="上月计划分析" align="center" prop="lastAnalyse"  :show-overflow-tooltip="true"
          min-width="90" />
      <el-table-column label="本月工作重点" align="center" prop="workFocus"  :show-overflow-tooltip="true"
      min-width="90" />
      <el-table-column label="本月主题活动" align="center" prop="themeActivities"  :show-overflow-tooltip="true"
      min-width="90" />
      <el-table-column label="本月家长工作" align="center" prop="parentWork"  :show-overflow-tooltip="true"
      min-width="90" />
      <el-table-column label="学校代码" align="center" prop="schoolCode"  :show-overflow-tooltip="true"
          min-width="90" />
      <el-table-column label="更新时间" align="center" prop="updateTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateWeek(scope.row)"
            >修改月份
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            >修改详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-opportunity"
            @click="handleView(scope.row)"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="deleteBtn(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" :before-close="cancel" :width="widths" append-to-body>
      <el-form v-if="isAdd==1||isAdd==2" ref="form" :model="form" :rules="rules" label-width="75px">
        <el-form-item label="学期" prop="semsterId">
        <el-select v-model="form.semsterId" filterable clearable placeholder="请选择学期">
          <el-option
            v-for="item in semsterList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="classId">
        <el-select v-model="form.classId" clearable filterable placeholder="请选择班级">
          <el-option
            v-for="item in classList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="月份" prop="monthTime">
          <el-date-picker v-model="form.monthTime" placeholder="请输入月份" type="month"
                value-format="yyyy-MM"/>
        </el-form-item>
        <el-form-item label="上月计划分析" prop="lastAnalyse">
          <el-input v-model="form.lastAnalyse" placeholder="请输入计划分析" />
        </el-form-item>
        <el-form-item label="本月工作重点" prop="workFocus">
          <el-input v-model="form.workFocus" placeholder="请输入工作重点" />
        </el-form-item>
        <el-form-item label="本月主题活动" prop="themeActivities">
          <el-input v-model="form.themeActivities" placeholder="请输入主题活动" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }"/>
        </el-form-item>
        <el-form-item label="本月家长工作" prop="parentWork">
          <el-input v-model="form.parentWork" placeholder="请输入家长工作" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }"/>
        </el-form-item>
      </el-form>
      <div v-else>
        <!-- <custom-table ref="customTableRef" :tableData='tableData' :dayList='dayList' :dataListLeft='dataListLeft'></custom-table> -->
        <month-table ref="monthTableRef" :tableData='tableData' :centerTable="centerTable"></month-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="isAdd==1||isAdd==2" @click="openMessageBox">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { getPlanList,addWorklyPlan,getWeekDetail,editWorklyPlan } from "@/api/teach/weeklyplan";
// import {getWeekDetail } from "@/api/teach/weeklyplan";
import { getPlanList,editMonthPlan,addMonthPlan,queryMonthDetails,monthplanDelete } from "@/api/teach/monthPlan";
import {
  getSpecialty,
} from "@/api/base/specialty";
import { selectSemster} from "@/api/base/semster";
import { selectClazz } from "@/api/base/clazz";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import CustomTable from "@/components/CustomTable/index.vue"
import monthTable from "@/components/monthTable/index.vue"
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Specialty",
  components: { Treeselect,CustomTable,monthTable },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 部门树选项
      deptOptions: [],
      // 专业表格数据
      weeklyplanList: [],
      // 教师数据
      teacherList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classId:null,
        monthId:''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        semsterId: [
          { required: true, message: "学期不能为空", trigger: "blur" },
        ],
        classId: [
          { required: true, message: "班级不能为空", trigger: "blur" },
        ],
        monthTime: [
          { required: true, message: "月份不能为空", trigger: "blur" },
        ],
        workFocus: [
          { required: true, message: "工作重点不能为空", trigger: "blur" },
        ],
        lastAnalyse: [
          { required: true, message: "计划分析不能为空", trigger: "blur" },
        ],
        themeActivities: [
          { required: true, message: "主题活动不能为空", trigger: "blur" },
        ],
        parentWork: [
          { required: true, message: "家长工作不能为空", trigger: "blur" },
        ],
      },
      // 学期数据
      semsterList: [],
      // 班级数据
      classList: [],
      dataList:[],
      dataListLeft:{},
      widths:'500px',
      tableData:[],
      centerTable:[],
      week:['周一','周二','周三','周四','周五','周六','周日'],
      // dayList: ['上午', '下午'],
      isAdd:1//新增1,编辑2,查看3
    };
  },
  created() {
    this.getList();
    this.getSemster();
    this.getClazz();
  },
  methods: {
      /** 提交按钮 */
      openMessageBox() {
        this.$confirm('是否同步该班级所在年级其他班级的数据?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          this.form.inType = 1
          this.submitForm()
          this.$refs.form.resetFields();
        }).catch(() => {
          this.form.inType = 0
          this.submitForm()
          this.$refs.form.resetFields();
        });
      },
      // 删除
      deleteBtn(row){
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const {code,msg} = await monthplanDelete(row.id)
          if(code === 200){
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }else{
            this.$message.error(msg)
          }

        })
      },
    async queryMonthDetails(row) {
      // console.log("行数据22",row)
      try {
        let params = {
          monthId:row.id,
        }
        const data = await queryMonthDetails(params);
        // console.log("行数据",data)
        // this.dataList = Object.entries(data.data.right).map(([key, value]) => ({ [key]: value }));
        const filteredData = data.data.filter(obj => obj.activityCurriculum === '五大领域园本课程');
        console.log("行数据",filteredData)
        this.centerTable = filteredData
        // const arr = [];
        // for (let i = 0; i < this.dataList.length; i++) {
        //     for (let key in this.dataList[i]){
        //         this.dataList[i][key].name = this.week[i]
        //         arr.push(this.dataList[i][key])
        //       // }
        //     }
        // }
        // 处理后端数据以适应 el-table 的数据结构
        // for (const date in arr) {
        //   const row = {
        //     date: arr[date].name,
        //     morningActivities: arr[date].morning,
        //     afternoonActivities: arr[date].afternoon
        //   };
          this.tableData.push(row);
        // }

        // this.dealData(1) // 处理上午的数据
        // this.dealData(2) // 处理下午 的数据

        console.log('this.tableData',this.tableData);
        // this.dataListLeft = data.data.left
        // this.total = data.total;
        this.open = true
      } catch (e) {
        console.log(e)
      }
    },
    dealData(num){
      // 获取一个星期所有morningActivities数组里面最多包含多少个对象，
      // 再把其他morningActivities里面push多少个空对象，每个morningActivities数组的长度一致
      const weekActivities = this.tableData
      let maxLength = 0;
        for (let i = 0; i < weekActivities.length; i++) {
          const activities =num==1? weekActivities[i].morningActivities:weekActivities[i].afternoonActivities;
          if (activities.length > maxLength) {
            maxLength = activities.length;
          }
        }

          // 在每个数组末尾添加空对象，直到数组长度一致
          for (let i = 0; i < weekActivities.length; i++) {
            const activities = num==1? weekActivities[i].morningActivities:weekActivities[i].afternoonActivities;
            while (activities.length < maxLength) {
              activities.push({
                activityType: "",
                activityName: "",
                activityTarget: ""
              });
            }
          }
    },
  /**班级*/
    async getClazz(){
      try {
        const {rows}=await selectClazz();
        this.classList = rows
      }catch (e) {
        console.log(e)
      }
    },
    /**学期*/
    async getSemster(){
      try {
        const { rows }=await selectSemster();
        this.semsterList =rows;
      }catch (e) {
        console.log(e)
      }
    },
    /** 查询月份列表 */
    getList() {
      this.loading = true;
      getPlanList(this.queryParams).then((response) => {
        this.weeklyplanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.tableData = []
      this.$refs.form.resetFields();
      this.monthTableRefDataIn()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isAdd = 1
      this.open = true;
      this.title = "添加月工作计划";
      this.widths ='500px'

    },
    // 修改月份
    handleUpdateWeek(row){

      this.isAdd = 2
      this.title = '修改月工作计划'
      this.form = row

      this.$set( this.form,'time',[row.startTime,row.endTime]);
      this.open=true;
      this.widths ='500px'
    },
    // 查看
    handleView(row){
      this.isAdd = 3
      this.title = '查看月工作计划'
      this.queryMonthDetails(row)
      this.widths = '900px'

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log("修改月计划",row);
       this.$router.push({
        path: '/gradenSystem/monthPlanEdit',
        query: {
          className:row.className,//班级名称
          monthTime:row.monthTime,//月份
          lastAnalysis:row.lastAnalyse,//上次分析
          themeActivities:row.themeActivities,//主题活动
          workFocus:row.workFocus,//工作重点
          parentWork:row.parentWork,//家长工作
          monthID:row.id,
          classId:row.classId,
          schoolCode:row.schoolCode
        },
      })
    },
    //monthTableRef组件里2个数据的初始化
    monthTableRefDataIn(){
      this.$refs['monthTableRef'].currentData={}
      this.$refs['monthTableRef'].currentIndex=0
      this.$refs['monthTableRef'].currentForIs=true
      this.tableData = []
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate((valid) => {

        if(valid){
          console.log("form",this.form)
          // this.form.startTime =this.form.time[0]
          // this.form.endTime =this.form.time[1]
          if (this.isAdd==1) {
            addMonthPlan(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.getList();
              this.open = false;
              this.monthTableRefDataIn()
            });
          }else if(this.isAdd==2){
            editMonthPlan(this.form).then(res =>{
              console.log("方法执行了",res.code =='200')
                if(res.code =='200'){
                  this.getList();
                  this.open = false;
                  this.monthTableRefDataIn()


                }
            })
          }
        }

      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
  .el-input{
    width: 100%!important;
  }
}
.el-form-item__content{
  width: 100%;
    .el-input {
      width: 100%;
    }

}

::v-deep .el-date-editor {
  width: 100%;
}
</style>
